package com.yanqu.road.server.webservice;

import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpServer;
import com.yanqu.road.utils.net.CrossNetConfigHelper;
import com.yanqu.road.utils.net.ServerNetConfig;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.xml.ws.Endpoint;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CrossWebServiceHelper {

	private static Logger logger = LogManager.getLogger(CrossWebServiceHelper.class.getName());

	private static CrossWebServiceHelper instance;

	private CrossWebServiceHelper() {
	}

	public synchronized static CrossWebServiceHelper getInstance() {
		if (null == instance) {
			instance = new CrossWebServiceHelper();
		}

		return instance;
	}

	public boolean start(int serverType) {
		ServerNetConfig netConfig = CrossNetConfigHelper.getServerNetConfig(serverType, 0);
		try {
			HttpServer server = HttpServer.create(new InetSocketAddress(netConfig.getAdminPort()), 0);
			ExecutorService threads = Executors.newFixedThreadPool(20);
			server.setExecutor(threads);
			server.start();

			Endpoint castleEndpoint = Endpoint.create(new GrossWebService());
			HttpContext castleContext = server.createContext("/crossws");
			castleEndpoint.publish(castleContext);

			return true;
		} catch (IOException e) {
			logger.error("CrossWebService init error", e);
		}

		return false;
	}
}
